import { defineStore } from 'pinia'
import request from '@/utils/request'

/**
 * 用户状态管理
 */
export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    userInfo: null,
    // 访问令牌
    token: localStorage.getItem('token') || '',
    // 刷新令牌
    refreshToken: localStorage.getItem('refreshToken') || ''
  }),

  getters: {
    /**
     * 是否已登录
     */
    isLoggedIn: (state) => !!state.token,
    
    /**
     * 用户名
     */
    username: (state) => state.userInfo?.username || '',
    
    /**
     * 用户ID
     */
    userId: (state) => state.userInfo?.id || null
  },

  actions: {
    /**
     * 用户登录
     * @param {Object} loginData 登录数据
     * @param {string} loginData.username 用户名
     * @param {string} loginData.password 密码
     */
    async login(loginData) {
      try {
        const response = await request.post('/auth/login', loginData)
        
        if (response.code === 200) {
          const { token, refreshToken, user } = response.data
          
          // 保存令牌
          this.token = token
          this.refreshToken = refreshToken
          this.userInfo = user
          
          // 持久化存储
          localStorage.setItem('token', token)
          localStorage.setItem('refreshToken', refreshToken)
          localStorage.setItem('userInfo', JSON.stringify(user))
          
          return response
        } else {
          throw new Error(response.message || '登录失败')
        }
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      }
    },

    /**
     * 用户登出
     */
    async logout() {
      try {
        // 调用登出接口
        if (this.token) {
          await request.post('/auth/logout')
        }
      } catch (error) {
        console.error('登出接口调用失败:', error)
      } finally {
        // 清除本地数据
        this.clearUserData()
      }
    },

    /**
     * 获取当前用户信息
     */
    async getCurrentUser() {
      try {
        const response = await request.get('/auth/current')
        
        if (response.code === 200) {
          this.userInfo = response.data
          localStorage.setItem('userInfo', JSON.stringify(response.data))
          return response.data
        } else {
          throw new Error(response.message || '获取用户信息失败')
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 如果获取用户信息失败，可能是token过期，清除登录状态
        this.clearUserData()
        throw error
      }
    },

    /**
     * 刷新令牌
     */
    async refreshAccessToken() {
      try {
        if (!this.refreshToken) {
          throw new Error('没有刷新令牌')
        }

        const response = await request.post('/auth/refresh', {
          refreshToken: this.refreshToken
        })

        if (response.code === 200) {
          const { token } = response.data
          this.token = token
          localStorage.setItem('token', token)
          return token
        } else {
          throw new Error(response.message || '刷新令牌失败')
        }
      } catch (error) {
        console.error('刷新令牌失败:', error)
        // 刷新失败，清除登录状态
        this.clearUserData()
        throw error
      }
    },

    /**
     * 清除用户数据
     */
    clearUserData() {
      this.userInfo = null
      this.token = ''
      this.refreshToken = ''
      
      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
      localStorage.removeItem('userInfo')
    },

    /**
     * 初始化用户状态
     */
    initUserState() {
      const token = localStorage.getItem('token')
      const refreshToken = localStorage.getItem('refreshToken')
      const userInfo = localStorage.getItem('userInfo')

      if (token) {
        this.token = token
      }
      if (refreshToken) {
        this.refreshToken = refreshToken
      }
      if (userInfo) {
        try {
          this.userInfo = JSON.parse(userInfo)
        } catch (error) {
          console.error('解析用户信息失败:', error)
          localStorage.removeItem('userInfo')
        }
      }
    }
  }
})